//
//  GuiderDetailVC.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/4/19.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "GuiderDetailVC.h"
#import "GuiderDetailCell.h"
#import "GuiderDetailHeaderView.h"
#import "LoginVC.h"
#import "LinePreDetailVC.h"
#import "BigPicVC.h"
@interface GuiderDetailVC ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,BigPicVCDelegate>

@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) NSMutableArray * dataSource;

@property (nonatomic, strong) UIBarButtonItem * whiteItem;

@property (nonatomic, strong) UIBarButtonItem * blueItem;

@property (nonatomic, strong) GuiderCardModel * guiderModel;

//@property (nonatomic, strong) UIBarButtonItem * backWhiteBtn;
//@property (nonatomic, strong) UIBarButtonItem * backBlackBtn;

@property (nonatomic)NSInteger pageno;

@end

@implementation GuiderDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //  setTintColor:[UIColor blackColor];
    self.barBGAlpha = 1;
    [self createCollection];
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:[UIColor whiteColor]];
    [self loadDataSource];
    [self setRightBtn];
}

- (void)dealloc {
    
    [MobClick event:@"9_1_1"];
}

- (UIBarButtonItem *)blueItem {
    if (!_blueItem) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 44, 44);
        [btn setImage:[UIImage imageNamed:@"likeblue"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"liked"] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(collectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn addTarget:self action:@selector(allevent:) forControlEvents:UIControlEventAllTouchEvents];
        _blueItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    
    return _blueItem;
}


//- (UIBarButtonItem *)backBlackBtn {
//    if (!_backBlackBtn) {
//       UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        backBtn.frame = CGRectMake(0, 0, 44, 44);
//        backBtn.backgroundColor = [UIColor redColor];
//         backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//        [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
//        _backBlackBtn = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
//    }
//    
//    return _backBlackBtn;
//}
//
//- (UIBarButtonItem *)backWhiteBtn {
//    if (!_backWhiteBtn) {
//        UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        backBtn.frame = CGRectMake(0, 0, 44, 44);
//        backBtn.backgroundColor = [UIColor redColor];
//        backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//        [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
//        _backWhiteBtn = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
//    }
//    
//    return _backWhiteBtn;
//}
- (UIBarButtonItem *)whiteItem {
    
    if (!_whiteItem) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 44, 44);
        [btn setImage:[UIImage imageNamed:@"likewhite"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"likedwhite"] forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(collectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn addTarget:self action:@selector(allevent:) forControlEvents:UIControlEventAllTouchEvents];
        _whiteItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    
    return _whiteItem;
}

- (void)allevent:(UIButton *)btn {
    
    btn.highlighted = NO;
}
- (void)setRightBtn {
    
    self.navigationItem.rightBarButtonItem =  self.blueItem;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self changeWithType:1];
    [MobClick beginLogPageView:@"9"];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self changeWithType:0];
    [MobClick endLogPageView:@"9"];
    
}
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    
    return _dataSource;
}

- (void)loadDataSource {
    
    @weakify(self);
    [NetAPIManager getGuiderDetailWith:self.guiderID start:@(self.pageno) count:@(9) block:^(GuiderCardModel *guider, NSError *error) {
        @strongify(self);
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        self.guiderModel = guider;
        
        if (guider.isfavor) {
            
            ((UIButton * ) self.blueItem.customView).selected = YES;
            ((UIButton * ) self.whiteItem.customView).selected = YES;
        } else{
            ((UIButton * ) self.whiteItem.customView).selected = NO;
            ((UIButton * ) self.blueItem.customView).selected = NO;
        }
       
        
        if (self.pageno == 0) {
            self.dataSource =  [NSMutableArray arrayWithArray:guider.lines];
            [self.collectionView.mj_header endRefreshing];
        
            if (guider.lines.count < 9) {
                self.collectionView.mj_footer = nil;
            } else {
                @weakify(self);
                self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                    @strongify(self);
                    [self loadDataSource];
                }];
                [self.collectionView setThemeStyle:ThemeStyleBlack];
            }
        }else {
            [self.dataSource addObjectsFromArray:guider.lines];
            [self.collectionView.mj_footer endRefreshing];
        }
        
        if (guider.lines.count < 9) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            
            [self.collectionView.mj_footer endRefreshing];
        }
        
        [self.collectionView reloadData];
        self.pageno ++;
    }];
    
}
- (void)createCollection {
    //创建自定义布局
    UICollectionViewFlowLayout  * layout = [[UICollectionViewFlowLayout alloc] init];
    
    // 设置UICollectionView中每个Item的size
    CGFloat width = ISiPhone5 ?  SCREEN_WIDTH - 90: SCREEN_WIDTH - 150;
    layout.itemSize = CGSizeMake(width, width * 5/3);
    //创建Collection
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:layout];
    
    _collectionView.dataSource = self;
    
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    // _collectionView.de
    [self.view addSubview:_collectionView];
    
    // ios 11  scrollvew 的位置调整
    if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior =UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [_collectionView registerNib:[UINib nibWithNibName:@"GuiderDetailCell" bundle:nil] forCellWithReuseIdentifier:@"GuiderDetailCell"];
    [_collectionView registerNib:[UINib nibWithNibName:@"GuiderDetailHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GuiderDetailHeaderView"];
    
    
    @weakify(self);
//    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        @strongify(self);
//        _pageno = 0;
//        [self loadDataSource];
//        [self.collectionView.mj_footer resetNoMoreData];
//    }];
    
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self);
        [self loadDataSource];
    }];
    [self.collectionView setThemeStyle:ThemeStyleBlack];
}

- (void)changeWithType:(NSInteger)type {
    
    if (type) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
//        self.navigationItem.backBarButtonItem = self.backWhiteBtn;
        self.navigationItem.rightBarButtonItem = self.blueItem;
        

        [self backBarButtonWithImageName:@"返回"];
    }else {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
//        self.navigationItem.backBarButtonItem = self.backBlackBtn;

//        [[UINavigationBar appearance] setBackIndicatorImage:[UIImage imageNamed:@"back"]];
//        [[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:[UIImage imageNamed:@"back"]];
        self.navigationItem.rightBarButtonItem = self.whiteItem;
        
        
        [self backBarButtonWithImageName:@"back"];
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat yOffset = self.collectionView.contentOffset.y;
    if (yOffset <= 64 ) {
        
        CGFloat aplha = yOffset /64;
        
        self.barBGAlpha = aplha;
        if (aplha >=1) {
            
            [self changeWithType:0];
        }else {
            
            [self changeWithType:1];
        }
        self.title = @"";
        
    }else {
        
        [self changeWithType:0];
        self.barBGAlpha = 1;
        self.title = self.guiderModel.realname;
    }
}

- (void)goBigPicVCWith:(NSString *)url {
    
    BigPicVC * vc = [[BigPicVC alloc] init];
    vc.imageArray = @[url];
    [self.navigationController pushViewController:vc animated:YES];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    GuiderDetailCell *cell;
    
    cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GuiderDetailCell" forIndexPath:indexPath];
    
    LineModel * model = self.dataSource[indexPath.row];
    
    [cell configDataWith:model];
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    GuiderDetailHeaderView * reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GuiderDetailHeaderView" forIndexPath:indexPath];
    
    reusableView.delegate = self;
    [reusableView configDataWithGuiderModel:self.guiderModel];
    
    // [reusableView.favourBtn addTarget:self action:@selector(collectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    return reusableView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    return CGSizeMake(SCREEN_WIDTH, 186 + kNavigationBarHeight);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat width = (SCREEN_WIDTH - 50)/3;
    return CGSizeMake(width, width + 45);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(15, 15, 15, 15);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    return 10;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    
    return 10;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    LineModel * model = self.dataSource[indexPath.row];
    
    NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
    
    for (UIViewController *vc in marr) {
        if ([vc isKindOfClass:[LinePreDetailVC class]]) {
            [marr removeObject:vc];
            break;
        }
    }
    self.navigationController.viewControllers = marr;
    LinePreDetailVC * vc = [IGUtils loadViewController:@"LinePreDetailVC" storyboard:@"LineDetail"];
    vc.lineid = model.lineid;
    [self.navigationController pushViewController:vc animated:YES];
    
//    if (model.type.integerValue == 1) {
//        
//        for (UIViewController *vc in marr) {
//            if ([vc isKindOfClass:[CityTourDetailVC class]]) {
//                [marr removeObject:vc];
//                break;
//            }
//        }
//        self.navigationController.viewControllers = marr;
//        [AppManager sharedManager].lineid = model.lineid;
//        CityTourDetailVC * vc = [[CityTourDetailVC alloc] init];
//        vc.lineID = model.lineid;
//        [self.navigationController pushViewController:vc animated:YES];
//        
//        [MobClick event:@"9_1_2"];
//        
//    }else {
//        for (UIViewController *vc in marr) {
//            if ([vc isKindOfClass:[ScenicPlayVC class]]) {
//                [marr removeObject:vc];
//                break;
//            }
//        }
//        self.navigationController.viewControllers = marr;
//        
//        ScenicPlayVC *playVC = [[ScenicPlayVC alloc] init];
//        
//        [AppManager sharedManager].lineid = model.lineid;
//        
//        [self.navigationController pushViewController:playVC animated:YES];
//        
//        [MobClick event:@"9_1_3"];
//    }
    
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)collectBtnClick:(UIButton *)favBtn {
    
    
    if (![UserManager sharedManager].token) {
        [self loginAction];
        return;
    }
    [ActivityIndicatorView showHUDAddedTo:self.view];
    [NetAPIManager collectWithType:CollectTypeGuider Id:self.guiderID block:^(id result, NSError *error) {
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        if (!error) {
            self.guiderModel.isfavor = [result boolValue];
            
            if (_delegate && [_delegate respondsToSelector:@selector(collectOrCancelGuiderWith:guiderID:)]) {
                [_delegate collectOrCancelGuiderWith:[result boolValue]guiderID:self.guiderID];
            }
            if ([result boolValue]) {
                
                ((UIButton * ) self.blueItem.customView).selected = YES;
                ((UIButton * ) self.whiteItem.customView).selected = YES;
                [IGUtils showToast:MYLocalizedString(@"GUIDELIST_FOLLOW", nil)];
                
                [MobClick event:@"9_0_1"];
                
            } else{
                ((UIButton * ) self.whiteItem.customView).selected = NO;
                ((UIButton * ) self.blueItem.customView).selected = NO;
                [IGUtils showToast:MYLocalizedString(@"GUIDELIST_FOLLOWCANCEL", nil)];
                
                [MobClick event:@"9_0_2"];
            }
        }
    }];
}

- (void)loginAction {
    
    LoginVC *loginVC = [LoginVC new];
    loginVC.delegate = self;
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:loginVC];
    [self presentViewController:nav animated:YES completion:nil];
}

@end
